<template>
	<div class="system-teacherUser-container layout-padding">
		<el-card shadow="hover" class="layout-padding-auto">
			<div class="system-teacherUser-search mb15">
				<el-input v-model="state.tableData.param.nickName" size="default" placeholder="请输入姓名" :prefix-icon="Search" style="max-width: 180px"> </el-input>
        <el-input v-model="state.tableData.param.userName" size="default" placeholder="请输入电话号码" :prefix-icon="Search" style="max-width: 180px;margin-left: 10px"> </el-input>
        <el-tree-select
            v-model="state.tableData.param.orgId"
            :data="state.tableData.sysOrgData"
            :render-after-expand="false"
            size="default"
            style="width: 400px;margin-left: 10px"
            filterable
            clearable
            placeholder="学校筛选"
            show-all-levels
        />
        <el-button size="default" type="primary" class="ml10" @click="getTableData()">
					<el-icon>
						<ele-Search />
					</el-icon>
					查询
				</el-button>
        <el-button size="default" type="warning" class="ml10" @click="clearParam()">
          <el-icon>
            <ele-RemoveFilled />
          </el-icon>
          清除筛选条件
        </el-button>
				<el-button size="default" type="success" class="ml10" @click="onOpenAddUser('add')">
					<el-icon>
						<ele-FolderAdd />
					</el-icon>
					新增老师
				</el-button>
        <el-button size="default" type="primary" class="ml10" @click="onOpenImport()">
          <el-icon>
            <Upload />
          </el-icon>
          批量导入
        </el-button>
			</div>
			<el-table :data="state.tableData.data" v-loading="state.tableData.loading" style="width: 100%">
        <el-table-column type="expand" >
          <template #default="scope">
            <el-row >
              <el-col :span="12" :offset="1">
                <el-text size="large" type="primary" style="margin-right: 10px">任教信息</el-text>
                <el-button size="default" type="success" class="ml10" @click="onOpenAddTeach('add',scope.row)" :disabled="scope.row.isDelete === 1">
                  <el-icon>
                    <ele-FolderAdd />
                  </el-icon>
                  新增任教信息
                </el-button>
              </el-col>
            </el-row>
            <el-row style="margin-top: 20px;">
              <el-col :span="11" :offset="1">
                <el-table :data="scope.row.teacherTeachList" v-loading="state.tableData.loading" style="" border>
                  <el-table-column label="班级" prop="orgName" width="350"/>
                  <el-table-column label="课程" prop="teachSubject" width="150"/>
                  <el-table-column prop="isDelete" label="状态" width="120" show-overflow-tooltip>
                    <template #default="scope1">
                      <el-tag type="success" v-if="scope1.row.isDelete==0">正常</el-tag>
                      <el-tag type="info" v-else>禁用</el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="125" >
                    <template #default="scope2">
                      <el-button :disabled="scope.row.isDelete === 1" size="small" text type="primary" @click="onOpenEditTeach('edit', scope.row,scope2.row)"
                      >修改</el-button
                      >
                      <el-button :disabled="scope2.row.isDelete === 1" size="small" text type="primary" @click="onRowTeachDel(scope2.row)">禁用</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
				<el-table-column type="index" label="序号" width="60" />
				<el-table-column prop="username" label="电话号码（帐号）" width="150" show-overflow-tooltip></el-table-column>
				<el-table-column prop="nickName" label="姓名" width="150" show-overflow-tooltip></el-table-column>
        <el-table-column prop="orgName" label="所在学校" width="200" show-overflow-tooltip></el-table-column>
				<el-table-column prop="gender" label="性别" width="100" show-overflow-tooltip>
          <template #default="scope">
            <el-tag effect="dark" v-if="scope.row.gender==0">男</el-tag>
            <el-tag effect="dark" type="danger" v-else-if="scope.row.gender==1">女</el-tag>
            <el-tag effect="dark" type="warning" v-else>未知</el-tag>
          </template>
        </el-table-column>
				<el-table-column prop="userIdCardNumber" label="证件号码" show-overflow-tooltip></el-table-column>
        <el-table-column prop="idType" label="证件类型" show-overflow-tooltip></el-table-column>
				<el-table-column prop="isDelete" label="老师状态" width="100" show-overflow-tooltip>
					<template #default="scope">
						<el-tag type="success" v-if="scope.row.isDelete==0">正常</el-tag>
						<el-tag type="info" v-else>禁用</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="gmtCreate" label="创建时间" show-overflow-tooltip></el-table-column>
				<el-table-column prop="gmtModified" label="修改时间" show-overflow-tooltip></el-table-column>
				<el-table-column label="操作" width="250">
					<template #default="scope">
            <el-button  size="small" text type="primary" @click="onOpenAuthorizeDialog(scope.row.id)" >授权管理</el-button>
						<el-button  size="small" text type="primary" @click="onOpenEditUser('edit', scope.row)"
							>修改</el-button
						>
						<el-button :disabled="scope.row.isDelete === 1" size="small" text type="primary" @click="onRowDel(scope.row)">删除</el-button>
            <el-button size="small" text type="primary" @click="resetPassword(scope.row)">重置密码</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				@size-change="onHandleSizeChange"
				@current-change="onHandleCurrentChange"
				class="mt15"
				:pager-count="5"
				:page-sizes="[10,20,50,100, 200, 500]"
				v-model:current-page="state.tableData.param.current"
				background
				v-model:page-size="state.tableData.param.pageSize"
				layout="total, sizes, prev, pager, next, jumper"
				:total="state.tableData.total"
			>
			</el-pagination>
		</el-card>
		<teacherUserDialog ref="teacherUserDialogRef" @refresh="getTableData()" />
    <teachDialog ref="teachDialogRef" @refresh="getTableData()" />
    <importDialog ref="importDialogRef" />
    <authorizeDialog ref="authorizeDialogRef" @refresh="getTableData()" />
	</div>
</template>

<script setup lang="ts" name="systemteacherUser">
import { defineAsyncComponent, reactive, onMounted, ref } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import {Search, Upload} from "@element-plus/icons-vue";
import {userApi} from "/@/api/user";
import {systemApi} from "/@/api/system";
const {orgSchoolOnlyTree} = systemApi();
const {teacherListByPage,teacherRemoveById,teachRemoveById,resetUserPassword} = userApi();

// 引入组件
const teacherUserDialog = defineAsyncComponent(() => import('/src/views/system/teacherUser/dialog.vue'));
const teachDialog = defineAsyncComponent(() => import('/src/views/system/teacherUser/dialogTeach.vue'));
const importDialog = defineAsyncComponent(() => import('/src/views/system/teacherUser/dialogImport.vue'));
const authorizeDialog = defineAsyncComponent(() => import('/src/views/system/noRole/authorizeDialog.vue'));
const authorizeDialogRef = ref();
// 定义变量内容
const teacherUserDialogRef = ref();
const teachDialogRef = ref();
const importDialogRef = ref();
const state = reactive<StudentSysUserState>({
	tableData: {
		data: [],
		total: 0,
		loading: false,
    sysOrgData: [],
		param: {
			current: 1,
			pageSize: 10,
      nickName:'',
      userName:'',
      orgId:'',
		},
	},
});

// 初始化表格数据
const getTableData = async () => {
  state.tableData.loading = true;
  const res = await teacherListByPage(state.tableData.param)
  if (res.status === 200) {
    state.tableData.data = res.data.records;
    state.tableData.total = res.data.total;
    state.tableData.loading = false;
  }
};

// 初始化机构数据
const getMenuData = async () => {
  const res = await orgSchoolOnlyTree()
  if (res.status === 200) {
    state.tableData.sysOrgData = res.data;
  }
};
const clearParam = () => {
  state.tableData.param.nickName = '';
  state.tableData.param.userName = '';
  state.tableData.param.orgId = '';
};
// 打开新增用户弹窗
const onOpenAddUser = (type: string) => {
  teacherUserDialogRef.value.openDialog(type);
};
// 打开修改用户弹窗
const onOpenEditUser = (type: string, row: RowStudentUserType) => {
  teacherUserDialogRef.value.openDialog(type, row);
};

const onOpenAddTeach = (type: string,teacherRow: RowStudentUserType) => {
  teachDialogRef.value.openDialog(type,teacherRow);
};
// 打开修改用户弹窗
const onOpenEditTeach = (type: string,teacherRow: RowStudentUserType,row: RowTeachType) => {
  teachDialogRef.value.openDialog(type, teacherRow,row);
};

const onOpenImport = () => {
  importDialogRef.value.openDialog();
};

const onOpenAuthorizeDialog = (userId: string) => {
  authorizeDialogRef.value.openDialog(userId);
};
// 删除用户
const onRowDel = (row: RowStudentUserType) => {
	ElMessageBox.confirm(`此操作将删除该用户的所有教师身份，账户名称：“${row.nickName}”，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
      const res = await teacherRemoveById({id: row.id})
      if (res.status === 200) {
        await getTableData();
        ElMessage.success('删除成功');
      } else {
        ElMessage.error('删除失败');
      }
    })
		.catch(() => {});
};
//删除任教信息
const onRowTeachDel = (row: RowTeachType) => {
  ElMessageBox.confirm(`此操作将禁用任教信息：“${row.orgName}的${row.teachSubject}课，老师为${row.teacherName}”，是否继续?`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
      .then(async () => {
        const res = await teachRemoveById({id: row.id})
        if (res.status === 200) {
          await getTableData();
          ElMessage.success('删除成功');
        } else {
          ElMessage.error('删除失败');
        }
      })
      .catch(() => {});
};
const resetPassword = (row: RowStudentUserType) => {
  ElMessageBox.confirm(`此操作将重置该用户的密码为默认密码，账户名称：“${row.nickName}”，是否继续?`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
      .then(async () => {
        const res = await resetUserPassword({id: row.id})
        if (res.status === 200) {
          ElMessage.success('重置成功');
        }else{
          ElMessage.error('重置失败');
        }
      })
      .catch(() => {});
};

// 分页改变
const onHandleSizeChange = (val: number) => {
	state.tableData.param.pageSize = val;
	getTableData();
};
// 分页改变
const onHandleCurrentChange = (val: number) => {
	state.tableData.param.pageNum = val;
	getTableData();
};
// 页面加载时
onMounted(() => {
	getTableData();
  getMenuData();
});
</script>

<style scoped lang="scss">
.system-teacherUser-container {
	:deep(.el-card__body) {
		display: flex;
		flex-direction: column;
		flex: 1;
		overflow: auto;
		.el-table {
			flex: 1;
		}
	}
}
</style>
